<template>
  <view class="container">
    <!-- 顶部标题栏及收货地址区域，添加 new-header-bg 类 -->
    <view class="new-header-bg">
      <!-- 顶部标题栏 -->
      <view class="header">
        <text class="title">确认订单</text>
      </view>
       <!-- 收货地址区域 -->
      <view class="address-block">
        <view class="address-title">收货地址</view>
        <view class="address-info" @click="navigateToAddress">
          <!-- 添加 v-if 进行非空判断 -->
          <view class="address-line1" v-if="selectedAddress">
            <text>{{ selectedAddress.city }}{{ selectedAddress.department }}{{ selectedAddress.houseNumber }}</text>
            <image class="arrow-icon" src="/static/icon/right.png" @click="navigateToAddress"></image>
          </view>
          <view class="address-line2" v-if="selectedAddress">
            <text>{{ selectedAddress.name }}</text>
            <text>{{ selectedAddress.phone }}</text>
          </view>
        </view>
      </view>
    </view>
    <!-- 内容区域 -->
    <view class="content">
      <!-- 商品信息区域 -->
      <view class="goods-block">
        <view class="store-name">{{ orderData.storeName }}</view>
        <!-- 使用 v-for 循环遍历商品列表 -->
        <view class="product-item" v-for="(item, index) in orderData.items" :key="index">
          <image class="product-img" :src="`/static/${item.imgUrl}`" mode="aspectFill" />
          <view class="product-details">
            <text class="product-name">{{ item.name }}</text>
            <view class="price-container">
              <text class="product-price">￥{{ item.price.toFixed(2) }} x {{ item.quantity }}</text>
              <text class="product-total-price">￥{{ getItemTotal(item).toFixed(2) }}</text>
            </view>
          </view>
        </view>
      </view>
      <!-- 显示下单时间和应付金额 -->
      <view class="order-info">
        <text class="info-label">下单时间：</text>
        <text class="info-value">{{ orderTime }}</text>
      </view>
      <view class="order-info">
        <text class="info-label">应付金额：</text>
        <text class="info-value">￥{{ orderData.totalPrice.toFixed(2) }}</text>
      </view>
    </view>
    <!-- 订单底部区域 -->
    <view class="footer-block">
      <view class="total-price-block">
        <text class="total-price-label">实付金额</text>
        <text class="total-price-value">￥{{ orderData.totalPrice.toFixed(2) }}</text>
      </view>
      <button
        class="submit-btn"
        :disabled="!selectedAddress"
        @click="submitOrder"
      >
        提交订单
      </button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      orderData: null,
      addressList: [],
      selectedAddress: null,
      currentTime: '',
      orderTime: '' // 新增下单时间属性
    };
  },
  onLoad(options) {
    // 解析从 address 页面传递过来的地址信息
    if (options && options.address && typeof options.address === 'string') {
      try {
        const address = JSON.parse(decodeURIComponent(options.address));
        if (typeof address === 'object' && address !== null) {
          this.selectedAddress = address;
        }
      } catch (error) {
        console.error('解析地址信息失败', error);
      }
    }
    this.loadAddressList();
    this.loadOrderData();
    // 获取当前时间并格式化
    this.updateCurrentTime();
    // 获取下单时间
    this.setOrderTime();
    // 每秒更新一次时间
    this.timeInterval = setInterval(() => {
      this.updateCurrentTime();
    }, 1000);
  },
  onHide() {
    // 页面隐藏时清除定时器
    clearInterval(this.timeInterval);
  },
  methods: {
    // 加载地址列表
    loadAddressList() {
      uni.request({
        url: 'https://67f85eae7719dfcd4b47e8f1.hz-iframe-svc.simplelab.cn/address',
        method: 'GET'
      })
     .then((res) => {
        if (Array.isArray(res.data) && res.data.length > 0) {
          this.addressList = res.data;
          // 更严谨地设置默认选中地址，避免未定义情况
          this.selectedAddress = res.data[0] || {};
        } else {
          // 如果没有获取到地址数据，设置为空对象避免报错
          this.selectedAddress = {};
        }
      })
     .catch((error) => {
        console.error('加载地址失败:', error);
        uni.showToast({
          title: '加载地址失败',
          icon: 'none'
        });
        // 加载失败时也设置为空对象
        this.selectedAddress = {};
      });
    },
    // 加载订单数据，从本地存储获取
    loadOrderData() {
      const selectedItems = uni.getStorageSync('selectedCartItems');
      if (selectedItems && selectedItems.length > 0) {
        const storeName = selectedItems[0].storeName;
        const totalPrice = selectedItems.reduce((sum, item) => sum + (item.price * item.quantity), 0);
        this.orderData = {
          storeName,
          items: selectedItems,
          totalPrice
        };
      }
    },
    // 跳转到地址列表页面
  navigateToAddress() {
    uni.navigateTo({
      url: '/pages/me/address?from=confirm'  // 添加来源标识
    });
  },
  
  // 在onShow中检查返回的地址
  onShow() {
    // 从缓存获取最新选择的地址
    const selectedAddress = uni.getStorageSync('selectedAddress');
    if (selectedAddress) {
      this.selectedAddress = selectedAddress;
      // 清除缓存，避免下次进入时误用
      uni.removeStorageSync('selectedAddress');
    }
  },
    // 提交订单
    submitOrder() {
      if (!this.orderData ||!this.selectedAddress) return;
      // 简单校验商品数量和价格
      const hasInvalidItem = this.orderData.items.some((item) => item.quantity <= 0 || item.price <= 0);
      if (hasInvalidItem) {
        uni.showToast({
          title: '商品信息有误，请检查',
          icon: 'none'
        });
        return;
      }

      uni.showModal({
        title: '确认要提交订单吗?',
        content: '请尽快完成支付，否则将被取消',
        confirmText: '确认提交',
        cancelText: '取消订单',
        success: (res) => {
          if (res.confirm) {
            const order = {
              shopId: this.orderData.items[0].storeId,
              address: this.selectedAddress,
              items: this.orderData.items,
              totalAmount: this.orderData.totalPrice,
              orderTime: this.orderTime // 添加订单时间
            };
            // 存储订单数据到本地存储，以便在 pay.vue 中使用
            uni.setStorageSync('tempOrderData', order);

            uni.request({
              url: 'https://67f85eae7719dfcd4b47e8f1.hz-iframe-svc.simplelab.cn/orders',
              method: 'POST',
              data: order
            })
           .then((res) => {
              console.log('订单数据:', order);
              uni.showToast({
                title: '下单成功',
                icon:'success'
              });
              // 清空本地存储的选中商品信息
              uni.removeStorageSync('selectedCartItems');
              // 下单成功后跳转支付页面
              uni.navigateTo({
                url: '/pages/must/pay'
              });
            })
           .catch((error) => {
              console.error('下单失败:', error);
              uni.showToast({
                title: '下单失败',
                icon: 'none'
              });
            });
          } else if (res.cancel) {
            // 这里可以添加取消订单相关逻辑，比如提示用户取消成功等
            uni.showToast({
              title: '已取消订单',
              icon: 'none'
            });
          }
        }
      });
    },
    // 获取单个商品总价
    getItemTotal(item) {
      return item.price * item.quantity;
    },
    // 更新当前时间
    updateCurrentTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hour = String(now.getHours()).padStart(2, '0');
      const minute = String(now.getMinutes()).padStart(2, '0');
      this.currentTime = `${year}-${month}-${day} ${hour}:${minute}`;
    },
    // 设置下单时间
    setOrderTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hour = String(now.getHours()).padStart(2, '0');
      const minute = String(now.getMinutes()).padStart(2, '0');
      this.orderTime = `${year}-${month}-${day} ${hour}:${minute}`;
    }
  }
};
</script>

<style scoped>
/* 全局样式 */
.container {
  display: flex;
  flex-direction: column;
  min-height: 95vh; /* 确保容器至少占满整个视口高度 */
}

/* 新增类，设置确认订单标题栏及收货地址区域渐变背景 */
.new-header-bg {
  background: linear-gradient(to bottom, #007BFF, white); /* 设置上蓝下白渐变背景 */
  position: relative;
}

/* 顶部标题栏 */
.header {
  height: 120rpx;
  display: flex;
  align-items: center;
  justify-content: center; /* 让子元素水平居中 */
  color: white;
  font-size: 36rpx;
  padding: 0 20rpx;
  position: relative;
}

.title {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* 让标题在父元素中垂直和水平居中 */
}

/* 显示当前时间的样式 */
.current-time {
  font-size: 24rpx;
  position: absolute;
  right: 20rpx;
  bottom: 20rpx;
}

/* 内容区域 */
.content {
  flex: 1; /* 内容区域自适应填充剩余空间 */
  overflow-y: auto; /* 内容过多时可滚动 */
}

/* 收货地址区域 */
.address-block {
  margin: 30rpx 20rpx;
  background-color: white; /* 保持收货地址背景为白色 */
  border-radius: 10rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.08);
  padding: 40rpx;
}
.address-title {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 10rpx;
}
.address-info {
  margin-top: 25rpx;
  font-size: 28rpx;
  color: #333;
}
.address-line1 {
  display: flex;
  align-items: center;
  margin-bottom: 5rpx;
}
.address-line2 {
  display: flex;
  align-items: center;
  color: #666;
  font-size: 25rpx;
}
.arrow-icon {
  width: 40rpx;
  height: 40rpx;
  margin-left: 10rpx;
}
/* 商品信息区域 */
.goods-block {
  margin: 20rpx;
  background-color: white;
  border-radius: 10rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.08);
  padding: 20rpx;
}
.store-name {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 10rpx;
}
.product-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx; /* 添加商品项之间的间距 */
}
.product-img {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}
.product-details {
  flex: 1;
}
.product-name {
  font-size: 30rpx;
  line-height: 1.4;
}
.price-container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.product-price {
  color: #e93b3b;
  font-size: 28rpx;
  margin-top: 20rpx;
  text-align: left;
}
.product-total-price {
  color: #333;
  font-size: 28rpx;
  margin-top: -30rpx;
  text-align: right;
}
/* 新增下单信息样式 */
.order-info {
  margin: 20rpx;
  background-color: white;
  border-radius: 10rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.08);
  padding: 20rpx;
  display: flex;
  align-items: center;
}
.info-label {
  font-size: 28rpx;
  color: #333;
  margin-right: 10rpx;
}
.info-value {
  font-size: 28rpx;
  color: #e93b3b;
}
/* 订单底部区域 */
.footer-block {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background-color: white;
}
.total-price-block {
  display: flex;
  align-items: center;
}
.total-price-label {
  font-size: 30rpx;
  color: #333;
  margin-right: 10rpx;
}
.total-price-value {
  font-size: 32rpx;
  color: #e93b3b;
  font-weight: bold;
}
.submit-btn {
  background: #0091ff;
  color: white;
  border-radius: 5rpx;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 32rpx;
  padding: 0 50rpx;
  margin-right: 50px;
 /* box-shadow: 0 4rpx 5rpx #0091ff;  */
}
</style>